#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-01-29 17:55:39

import logging
import logging.config


def getLoggerByConfig(config_file, logger_name):
    logging.config.fileConfig(config_file)
    logger = logging.getLogger(logger_name)
    return logger


def getLogger(logger_name,
              log_handler,
              log_level,
              log_format,
              log_file='test.log'):
    '''
    自定义logger名字，
    处理方式
    日志等级
    日志格式
        日志格式变量:
     |  %(name)s            Name of the logger (logging channel)
     |  %(levelno)s         Numeric logging level for the message (DEBUG, INFO,
     |                      WARNING, ERROR, CRITICAL)
     |
     |  %(name)s            Name of the logger (logging channel)
     |  %(levelno)s         Numeric logging level for the message (DEBUG, INFO,
     |                      WARNING, ERROR, CRITICAL)
     |  %(levelno)s         Numeric logging level for the message (DEBUG, INFO,
     |                      WARNING, ERROR, CRITICAL)
     |  %(levelname)s      Text logging level for the message ("DEBUG", "INFO",
     |                      "WARNING", "ERROR", "CRITICAL")
     |  %(pathname)s        Full pathname of the source file where the logging
     |                      call was issued (if available)
     |  %(filename)s        Filename portion of pathname
     |  %(module)s          Module (name portion of filename)
     |  %(lineno)d         Source line number where the logging call was issued
     |                      (if available)
     |  %(funcName)s        Function name
     |  %(created)f         Time when the LogRecord was created (time.time()
     |                      return value)
     |  %(asctime)s         Textual time when the LogRecord was created
     |  %(msecs)d           Millisecond portion of the creation time
     | %(relativeCreated)d Time in milliseconds when the LogRecord was created,
     |                      relative to the time the logging module was loaded
     |                      (typically at application startup time)
     |  %(thread)d          Thread ID (if available)
     |  %(threadName)s      Thread name (if available)
     |  %(process)d         Process ID (if available)
     |  %(message)s         The result of record.getMessage(), computed just as
     |                      the record is emitted
    '''
    logger = logging.getLogger(logger_name)
    # 定义处理方式，是文件还是stream(输出都屏幕上)
    if log_handler == 'file':
        hand = logging.FileHandler(log_file)
    elif log_handler == 'stream':
        hand = logging.StreamHandler()
    else:
        return 'error'

    # 设置日志等级
    hand.setLevel(log_level)
    # 设置格式
    formatter = logging.Formatter(log_format)
    # 将格式对象和处理方式对象添加到logger中
    hand.setFormatter(formatter)
    logger.addHandler(hand)
    return logger
